'use client';

import { useState, useRef, useEffect } from 'react';
import Image from 'next/image';
import styles from './TravelAssistant.module.css';

interface Message {
  id: string;
  content: string;
  isUser: boolean;
  timestamp: number;
}

const TravelAssistant: React.FC = () => {
  const [messages, setMessages] = useState<Message[]>([
    {
      id: '1',
      content: '你好！我是你的旅游助手，可以为你提供旅游目的地推荐、行程规划、景点介绍等信息。请告诉我你想去哪里旅游，或者你对哪个城市感兴趣？',
      isUser: false,
      timestamp: Date.now(),
    },
  ]);
  const [inputMessage, setInputMessage] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [streamingMessage, setStreamingMessage] = useState('');
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 滚动到最新消息
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages, streamingMessage]);

  // 处理发送消息
  const handleSendMessage = async () => {
    if (!inputMessage.trim()) return;

    // 添加用户消息
    const userMessage: Message = {
      id: Date.now().toString(),
      content: inputMessage,
      isUser: true,
      timestamp: Date.now(),
    };

    setMessages((prev) => [...prev, userMessage]);
    setInputMessage('');
    setIsLoading(true);
    setStreamingMessage('');

    try {
      // 调用API获取流式响应
      const response = await fetch('/api/travel-assistant', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ prompt: inputMessage }),
      });

      // 检查是否为JSON响应（通常是错误消息）
      const contentType = response.headers.get('content-type');
      if (contentType && contentType.includes('application/json')) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'API请求失败');
      }

      if (!response.ok) {
        throw new Error(`API请求失败: ${response.status}`);
      }

      // 处理流式响应
      const reader = response.body?.getReader();
      if (!reader) throw new Error('无法读取响应');

      let accumulatedContent = '';
      // 创建一个明确指定UTF-8编码的TextDecoder实例
      const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: false });

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        // 使用固定的decoder实例解码接收到的数据块
        try {
          const chunk = decoder.decode(value, { stream: true });
          accumulatedContent += chunk;
          setStreamingMessage(accumulatedContent);
        } catch (decodeError) {
          console.error('解码响应数据时出错:', decodeError);
          throw new Error('解码响应数据时出错，可能是字符编码问题');
        }
      }
      
      // 确保处理最后的数据
      try {
        const finalChunk = decoder.decode(undefined, { stream: false });
        if (finalChunk) {
          accumulatedContent += finalChunk;
          setStreamingMessage(accumulatedContent);
        }
      } catch (finalDecodeError) {
        console.error('解码最终数据时出错:', finalDecodeError);
      }

      // 流式响应完成后，添加助手消息
      const assistantMessage: Message = {
        id: Date.now().toString(),
        content: accumulatedContent,
        isUser: false,
        timestamp: Date.now(),
      };

      setMessages((prev) => [...prev, assistantMessage]);
      setStreamingMessage('');
    } catch (error) {
      console.error('获取旅游助手响应失败:', error);
      // 添加错误消息
      const errorMessage: Message = {
        id: Date.now().toString(),
        content: error instanceof Error && error.message ? 
          error.message : 
          '抱歉，我遇到了一些问题，无法回答你的问题。请稍后再试。',
        isUser: false,
        timestamp: Date.now(),
      };
      setMessages((prev) => [...prev, errorMessage]);
    } finally {
      setIsLoading(false);
    }
  };

  // 处理按键事件
  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  // 格式化时间
  const formatTime = (timestamp: number) => {
    const date = new Date(timestamp);
    return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  };

  return (
    <div className={styles.travelAssistant}>
      <div className={styles.header}>
        <div className={styles.avatar}>
          <Image 
            src="/travel-assistant-avatar.svg" 
            alt="旅游助手" 
            width={40} 
            height={40}
            onError={(e) => {
              // 如果图片加载失败，使用默认图片
              const target = e.target as HTMLImageElement;
              target.src = 'https://placehold.co/40x40?text=TA';
            }}
          />
        </div>
        <div className={styles.title}>旅游助手</div>
      </div>

      <div className={styles.messagesContainer}>
        {messages.map((message) => (
          <div 
            key={message.id} 
            className={`${styles.messageWrapper} ${message.isUser ? styles.userMessage : styles.assistantMessage}`}
          >
            <div className={styles.messageBubble}>
              <div className={styles.messageContent}>{message.content}</div>
              <div className={styles.messageTime}>{formatTime(message.timestamp)}</div>
            </div>
          </div>
        ))}

        {/* 流式响应中的消息 */}
        {streamingMessage && (
          <div className={`${styles.messageWrapper} ${styles.assistantMessage}`}>
            <div className={styles.messageBubble}>
              <div className={styles.messageContent}>{streamingMessage}</div>
            </div>
          </div>
        )}

        {/* 加载指示器 */}
        {isLoading && !streamingMessage && (
          <div className={`${styles.messageWrapper} ${styles.assistantMessage}`}>
            <div className={styles.messageBubble}>
              <div className={styles.loadingIndicator}>
                <div className={styles.loadingDot}></div>
                <div className={styles.loadingDot}></div>
                <div className={styles.loadingDot}></div>
              </div>
            </div>
          </div>
        )}

        <div ref={messagesEndRef} />
      </div>

      <div className={styles.inputContainer}>
        <textarea
          className={styles.inputField}
          value={inputMessage}
          onChange={(e) => setInputMessage(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder="输入你的旅游问题..."
          rows={1}
        />
        <button 
          className={styles.sendButton} 
          onClick={handleSendMessage}
          disabled={isLoading || !inputMessage.trim()}
        >
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z" fill="currentColor"/>
          </svg>
        </button>
      </div>
    </div>
  );
};

export default TravelAssistant;